using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

[CreateAssetMenu(fileName = "ItemDatabase", menuName = "DataSO/Item Database")]
public class ItemDatabase : ScriptableObject
{
    public string databaseName;
    public string databaseVersion;
    public List<ItemConfigData> items;

    public void UpdateData(string json)
    {
        var itemsList = JsonConvert.DeserializeObject<List<ItemConfigDataJson>>(json);
        items = itemsList.Select(i => new ItemConfigData
        {
            itemId = i.itemId,
            itemName = i.itemName,
            type = i.type,
            rarity = Enum.TryParse<Rarity>(i.rarity, out var r) ? r : Rarity.unknown,
            iconPath = i.iconPath,
            description = i.description
        }).ToList();
        items.Sort((a, b) => b.rarity.CompareTo(a.rarity));
    }

    [System.Serializable]
    private class ItemConfigDataJson
    {
        public string itemId;
        public string itemName;
        public string type;
        public string rarity;
        public string iconPath;
        public string description;
    }


    public ItemConfigData GetItemById(string itemId)
    {
        return items.Find(item => item.itemId == itemId);
    }
}

[System.Serializable]
public class ItemConfigDataJson
{
    public string itemId;
    public string itemName;
    public string type;
    public string rarity;
    public string iconPath;
    public string description;
}

public enum Rarity { unknown, normal, rare, epic, legendary }

[System.Serializable]
public class ItemConfigData
{
    public string itemId;
    public string itemName;
    public string type;
    public Rarity rarity;
    public string iconPath;
    public string description;
}